<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;

/**
 * 邀请人列表
 *
 * @icon fa fa-circle-o
 */
class Invited extends Backend
{

    /**
     * Club模型对象
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 处理身份搜索的特殊逻辑
            $identitySearch = false;
            $identityValue = '';

            $filter = json_decode($this->request->get("filter", ''), true);
            $op     = json_decode($this->request->get("op", '', 'trim'), true);
            if (isset($filter['identity.identity_type'])&&$filter['identity.identity_type'] == '普通用户') {
                $identityValue = $filter['identity.identity_type'];
                if($identityValue == '普通用户'){
                    $identitySearch = true;
                }
                unset($filter['identity.identity_type']);
                unset($op['identity.identity_type']);
                // 重新设置请求参数
                $this->request->get(['filter' => json_encode($filter)]);
                $this->request->get(['op' => json_encode($op)]);
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $param = $this->request->param();
            $dtl_where = ' 1=1';
            if(isset($param['ids'])&&$param['ids']){
                if ($identitySearch && $identityValue == '普通用户') {
                    $dtl_where .= ' and fa_user.p_user_id = ' . $param['ids'];
                }else{
                    $dtl_where .= ' and user.p_user_id = ' . $param['ids'];
                }
            }

            // 如果搜索的是普通用户，需要特殊处理
            if ($identitySearch && $identityValue == '普通用户') {
                // 使用 LEFT JOIN 来查找没有身份信息的用户
                $list = $this->model
                    ->join('identity_info identity', 'fa_user.id = identity.user_id', 'LEFT')
                    ->where($where)->where($dtl_where)
                    ->where(function($query) {
                        $query->whereNull('identity.user_id')
                            ->whereOr('identity.identity_type', 'null')
                            ->whereOr('identity.identity_type', '');
                    });
            } else {
                // 正常查询，使用关联
                $list = $this->model
                    ->with(['group','identity'])
                    ->where($where)->where($dtl_where);
            }

            // 如果进行了身份搜索，需要选择正确的字段并处理关联数据
            if ($identitySearch) {
                if ($identitySearch && $identityValue == '普通用户') {
                    $list = $list->field('fa_user.*,COALESCE(identity.identity_type,"普通用户") as identity_type')->order($sort, $order)->paginate($limit);
                }else{
                    $list = $list->field('user.*,COALESCE(identity.identity_type,"普通用户") as identity_type')->order($sort, $order)->paginate($limit);
                }
                // 手动加载关联数据
                foreach ($list as $item) {
                    $item->group = \app\admin\model\UserGroup::get($item->group_id);
                    $item->identity = \app\admin\model\IdentityInfo::where('user_id', $item->id)->find();
                }
            } else {
                $list = $list->order($sort, $order)->paginate($limit);
            }

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $this->model->where(['id'=>$ids])->update(['p_user_id'=>null]);
        $this->success();
    }
}
